package com.seven.leetcode.problems;

import com.seven.leetcode.utils.TreeNode;

import java.util.Arrays;
import java.util.Objects;

/**
 * 897. 递增顺序搜索树
 * https://leetcode-cn.com/problems/increasing-order-search-tree/
 * 级别：Easy
 * <p>
 * 给你一棵二叉搜索树，请你 按中序遍历 将其重新排列为一棵递增顺序搜索树，使树中最左边的节点成为树的根节点，并且每个节点没有左子节点，只有一个右子节点。
 * <p>
 * 示例 1：
 * 输入：root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
 * 输出：[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
 * <p>
 * 示例 2：
 * 输入：root = [5,1,7]
 * 输出：[1,null,5,null,7]
 * <p>
 * 提示：
 * 树中节点数的取值范围是 [1, 100]
 * 0 <= Node.val <= 1000
 *
 * @author : wenguang
 * @date : 2021/3/22 9:26
 */
public class IncreasingOrderSearchTree {

    static TreeNode temp = new TreeNode();

    public static void main(String[] args) {
        Integer[] nums = new Integer[]{5, 3, 6, 2, 4, null, 8, 1, null, null, null, 7, 9};
        TreeNode treeNode = TreeNode.fromArray(nums);
        System.out.println("in: " + Arrays.toString(nums));
        System.out.println("in: " + treeNode);
        TreeNode result = increasingBST(treeNode);
        System.out.println("out: " + result);
    }

    public static TreeNode increasingBST(TreeNode root) {
        TreeNode head = new TreeNode(0, null, temp);
        dfs(root);

        return head.right.right;
    }

    private static void dfs(TreeNode node) {
        if (null == node) {
            return;
        }

        boolean isLeft = Objects.isNull(node.left);
        boolean isRight = Objects.isNull(node.right);

        if (isLeft && isRight) {
            temp.right = new TreeNode(node.val);
            temp = temp.right;
        } else {
            if (!isLeft) {
                dfs(node.left);
            }

            temp.right = new TreeNode(node.val);
            temp = temp.right;

            dfs(node.right);
        }
    }
}
